/*!
 *  @author  xiaody <xiaody09@163.com>
 *  @runat  document-start
 */


var younight = +localStorage.younight || 1, yousign = +localStorage.yousign || 1;

(function(){

	'use strict';

	var getConfig = Config.get;

	// Insert a style element for later use.
	var sty = document.createElement('link');
	sty.setAttribute('rel', 'stylesheet');
	sty.setAttribute('data-ext', '_BDB_style_');

	// Choose day-mode or night-mode.
	if( getConfig('nightMode') && younight === -1 )
		sty.setAttribute('href', chrome.extension.getURL('tieba/css/night.css'));
	else if(getConfig('youColor'))
		sty.setAttribute('href', chrome.extension.getURL('tieba/css/day.css'));
	else
		sty.setAttribute('href', 'data:,');

	document.documentElement.appendChild(sty);


	var cssHideSelectors = [], cssHidePatch = [];
	// Block signatures if need.
	if( getConfig('signSwitch') && yousign === -1 && /[cpf]/i.test(pathhead) ) {
		blockBySrc(/\?v=tbs$/);
		cssHideSelectors = ['.d_sign_split','.d_sign_split+img','.d_sign_spacer','.sign_split','.sign_split+img'];
	}

	// Display module.
	var choices = ConfigContent.displayGroup.checkBoxes;
	for(var i = choices.id.length; i--;) {
		if(getConfig(choices.id[i])) {
			cssHideSelectors.push(choices.selector[i]);
		}
	}

	if(cssHideSelectors.length) {
		execCSS(cssHideSelectors.join(',') + '{display:none!important}', sty);
	}


	// Single tab browse mode.
	if( Config.get('singleTab') ) {
		document.addEventListener('mousedown', function(e){
			"use strict";
			var link = e.target;
			if(link.tagName !== 'A' || !link.host)
				return;
			if(link.host !== location.host)
				return;
			else if( link.getAttribute('target') === '_blank' && self === top )
				link.removeAttribute('target');
		}, true);
	}


	// Apply a piece of CSS in current document.
	function execCSS(cssText, styleElem){
		'use strict';

		if(!cssText)
			return;

		// Avoid race conditions.
		styleElem = styleElem || document.styleSheets[0];
		if(styleElem && styleElem.sheet)
			styleElem.sheet.insertRule(cssText, 0);
		else
			setTimeout(function(){execCSS(cssText, styleElem)}, 0);
	}


	// If there is no config setting in localStorage,
	// check file system.
	if(typeof localStorage['__BDB_configSetting__'] === 'undefined') {
		File.read('BDB_configSetting.txt', {
			success : function(data){
				if(data) {
					window.stop();
					localStorage['__BDB_configSetting__'] = data;
					location.reload();
				}
			}
		});
	}

})();